package com.tuoyu.peopletest.utils;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 文件操作
 */
public class SCFileUtils {
    private final static String TAG = "SCFileUtils";
    private final static String mucic_cache_file = "sc_music";

    public static File getMusicCachePath(Context context) {
        File filesDir = context.getFilesDir();
        File file = new File(filesDir, mucic_cache_file);
        if (file.exists()) {
            return file;
        }
        file.mkdir();
        return file;
    }

    /**
     * 删除一个文件
     *
     * @param file
     */
    public static void clearMusicFile(File file) {
        if (file.exists()) {
            SCLogUtils.e(TAG, "删除文件=" + file.getAbsolutePath());
            file.delete();
        }

    }


    public static File getSaveFile(Context context) {
        File file = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            file = Environment.getExternalStorageDirectory();
        } else {
            file = context.getFilesDir();
        }

        if (file != null) {
            file = new File(file, "pregnanttest");
            if (!file.exists()) {
                file.mkdir();
            }
        }

        return file;
    }

    /**
     * 导出文件
     *
     * @param context
     * @return
     */
    public static File getSaveOutFile(Context context) {
        File file = getSaveFile(context);
        if (file != null) {
            file = new File(file, "user_test");
            if (!file.exists()) {
                file.mkdir();
            }
        }
        return file;
    }

    public static File getSaveHrvFile(Context context) {
        File file = getSaveFile(context);
        if (file != null) {
            file = new File(file, "hrvtest");
            if (!file.exists()) {
                file.mkdir();
            }
        }
        return file;
    }

    public static void setObje2Local(File file, Object obj) {
        ObjectOutputStream oout = null;
        try {
            oout = new ObjectOutputStream(new FileOutputStream(file));
            oout.writeObject(obj);
            oout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Object getObje4Local(String path) {
        try {
            ObjectInputStream oin = new ObjectInputStream(new FileInputStream(new File(path)));
            Object object = oin.readObject(); // 强制转换到Person类型
            oin.close();
            return object;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }
}
